package com.ayh.campusfun.common.service.impl;

import com.ayh.campusfun.common.PageResult;
import com.ayh.campusfun.common.dao.BaseDao;
import com.ayh.campusfun.common.service.BaseService;
import com.ayh.campusfun.common.utils.PageUtil;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 基础数据库访问层
 *
 * @author ayh
 * @since 2021-03-19 18:19:01
 */

public class BaseServiceImpl<T> implements BaseService<T> {

    @Autowired
    private BaseDao<T> baseDao;

    @Override
    public Long insert(T t) {
        return baseDao.insert(t);
    }

    @Override
    public List<T> insertBatch(List<T> entities) {
        return baseDao.insertBatch(entities);
    }

    @Override
    public List<T> insertOrUpdateBatch() {
        return baseDao.insertOrUpdateBatch();
    }

    @Override
    public Long updateById(T t) {
        return baseDao.updateById(t);
    }

    @Override
    public Long updateBatch(List<T> entities) {
        return baseDao.updateBatch(entities);
    }

    /**
     * 列表
     * @param params
     * @return
     */
    @Override
    public PageResult<T> findAll(Map<String, Object> params){
        PageUtil.pageParamConver(params, true);
        List<T> list  =  baseDao.findListByParam(params);
        PageInfo<T> pageInfo = new PageInfo(list);
        Long count = baseDao.getCountByParam(params);
        Integer length = MapUtils.getInteger(params, "limit");
        int pages = (int) Math.ceil((double) count / (double) length);
        return PageResult.<T>builder().data(pageInfo.getList()).code(0).count(count).pages(pages).build();
    }

    @Override
    public List<T> findListByParam(Map<String, Object> map) {
        return baseDao.findListByParam(map);
    }

    @Override
    public T findById(Long id) {
        return baseDao.findById(id);
    }

    @Override
    public T findByParam(Map<String, Object> map) {
        return baseDao.findByParam(map);
    }

    @Override
    public Long getCountByParam(Map<String, Object> map) {
        return baseDao.getCountByParam(map);
    }

    @Override
    public Long getCount() {
        return baseDao.getCount();
    }

    @Override
    public Long deleteById(Long id) {
        return baseDao.deleteById(id);
    }

    @Override
    public Long deleteByParam(Map<String, Object> map) {
        return baseDao.deleteByParam(map);
    }

    @Override
    public Long deleteByIds(Long... ids) {
        return baseDao.deleteByIds(ids);
    }
}
